package com.lwl.concurrency.thread;

import java.util.concurrent.TimeUnit;

/**
 * wait.suspend(); / wait.resume(); 这两个方法已经被弃用
 * 线程暂停的同时并不会释放任何资源,此时,任何线程想访问被它暂用的锁时
 * 都会被挂起,导致无法继续执行,直到对应的线程上进行了resume()操作,被挂起的线程才能继续
 * 如果线程的resume()方法在suspend()方法前调用将会导致suspend()一直处于Runnable状态
 * 除非在suspend()方法被调用后再次调用resume();
 */
public class BadSuspend {

    ChangeObjectThread changeObjectThread1 = new ChangeObjectThread("changeObjectThread1");
    ChangeObjectThread changeObjectThread2 = new ChangeObjectThread("changeObjectThread2");

    public static void main(String[] args) throws InterruptedException {
        new BadSuspend().test2();
    }

    public void test2() throws InterruptedException {

        changeObjectThread1.start();
        Thread.sleep(100);
        changeObjectThread1.resume();

        changeObjectThread2.start();
        System.out.println("changeObjectThread2 start");
        changeObjectThread2.resume();

        //之前的调用的resume()可能运行在线程的挂起方法suspend()之前,导致resume()方法调用无效
        //如果不隔一段时间调用再次调用resume(),线程可能一直处于runnable状态.
        TimeUnit.SECONDS.sleep(2);
        System.out.println("再次调用changeObjectThread2 resume");
        changeObjectThread2.resume();

        changeObjectThread1.join();
        changeObjectThread2.join();

    }


    public class ChangeObjectThread extends Thread {

        public ChangeObjectThread(String name) {
            super(name);
        }

        @Override
        public void run() {
            //synchronized (object) {
            System.out.println("start in " + getName());
            Thread.currentThread().suspend();
            System.out.println("end in " + getName());
            //}
        }
    }


}
